package network;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class SocketConnection implements AutoCloseable{
    private Socket requestSocket;
    private ObjectInputStream inputStream;
    private ObjectOutputStream outputStream;

     public SocketConnection(Socket requestSocket) throws IOException {
         setRequestSocket(requestSocket);
         setOutputStream(new ObjectOutputStream(this.requestSocket.getOutputStream()));
         setInputStream(new ObjectInputStream(this.requestSocket.getInputStream()));
     }

    public Socket getRequestSocket() {
        return requestSocket;
    }

    public void setRequestSocket(Socket requestSocket) {
        this.requestSocket = requestSocket;
    }

    public void setInputStream(ObjectInputStream inputStream) {
        this.inputStream = inputStream;
    }

    public void setOutputStream(ObjectOutputStream outputStream) throws IOException {
        this.outputStream = outputStream;
        this.outputStream.flush();
    }

    public Object read() throws IOException, ClassNotFoundException {
        return inputStream.readObject();
    }

    public void write(Object message) throws IOException {
        outputStream.writeObject(message);
        outputStream.flush();
    }

    @Override
    public void close() throws IOException {
        inputStream.close();
        outputStream.close();
        requestSocket.close();
    }
}
